<?php

namespace app\common\model\worker;

use app\common\model\BaseModel;
use app\common\model\node\NodeModel;


class CustomerAuthModel extends BaseModel
{
    protected $table = 'customer_auth';


    /**
     * 指派人员
     * @param $Id
     * @param $adminData
     * @param string $type
     */
    public function appointAuth($customerId,$orderId=0,$adminData,$adminId){
        $type = $orderId>0?2:1;
        $nodeModel = new NodeModel();
        $taskModel = new TaskModel();
        $nodeList = $nodeModel->getNodeList($type);//获取节点
        $authList = $this->where('customer_id',$customerId)->where('order_id',$orderId)->column('*','node_id');
        foreach ($adminData as $k=>$v){
            $nodeItem = $nodeList[$v['node_id']];
            $map = [];
            $map[] = ['customer_id','=',$customerId];
            $map[] = ['order_id','=',$orderId];
            $map[] = ['node_id','=',$v['node_id']];
            $map[] = ['process_status','=',0];
            if($v['admin_id']>0 || (isset($v['audit_admin_id']) && $v['audit_admin_id']>0)){
                $item = [
                    'customer_id'=>$customerId,
                    'order_id'=>$orderId,
                    'node_id'=>$v['node_id'],
                    'admin_id'=>$v['admin_id'],
                    'action_admin_id'=>$adminId,
                    'action_time'=>date('Y-m-d H:i:s')
                ];
                if(isset($authList[$v['node_id']])){
                    $authData[] = array_merge($item,['id'=>$authList[$v['node_id']]['id']]);
                }else{
                    $authData[] = $item;
                }
                //todo 更改未完成任务的执行人和审核人
                $taskModel->where($map)->update([
                    'receive_admin_id'=>$item['admin_id'],
                    'admin_id'=>$adminId,
                ]);
            }else{
                //todo 删除相应权限 删除未执行的任务
                if(isset($authList[$v['node_id']])){
                    $this->where('id',$authList[$v['node_id']]['id'])->delete();
                    $taskModel->where($map)->delete();
                }
            }
        }
        if(!empty($authData)){
            $this->saveAll($authData);
        }
    }
    //跟客户有关系的员工
    public function relationCustomer(array $data){
        $data = [
            'customer_id' => $data['customer_id'],
            'admin_id' => $data['admin_id'],
            'role' => 'relation',//关系
            'action_admin_id' => $data['audit_admin_id'],
            'action_time' => date('Y-m-d H:i:s', time()),
        ];
        if($this->create($data)){
            return true;
        }
        return false;

    }

}
